﻿using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using static UnityEngine.RuleTile.TilingRuleOutput;

public class BaseObjCtrler : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    public MainUIEngine uIEngine { get; set; }
    [SerializeField] Image backImage;              // 改变背景图片
    [SerializeField] AudioClip audioPress;         // 按下音效
    [SerializeField] AudioSource audioPlayer;      // 音效播放器
    [SerializeField] ParticleSystem clickParticle;  // 点击粒子效果
    /// <summary>
    /// 鼠标按下的接口函数
    /// </summary>
    /// <param name="eventData"></param>
    public void OnPointerDown(PointerEventData eventData)
    {
        if (uIEngine.baseObj && uIEngine.baseObj != this)
        {
            //已经有选中的对象，则将该对象选中效果还原；
            uIEngine.baseObj.UnSelected();
        }
        else
        {
            uIEngine.baseObj = this;
        }
        //选中效果对象
        uIEngine.baseObj.Selected();
        //播放按钮点击声音
        PlayAudio();
        //播放粒子动画
        PlayClickParticle();
        
    }

    /// <summary>
    /// 鼠标抬起的接口函数
    /// </summary>
    /// <param name="eventData"></param>
    public void OnPointerUp(PointerEventData eventData)
    {
      
    }

    /// <summary>
    /// 选中该对象
    /// </summary>
    public void Selected()
    {
        backImage.color = Color.yellow;
        transform.localScale = Vector3.one * 1.2f;
    }

    /// <summary>
    /// 取消选中该对象
    /// </summary>
    public void UnSelected()
    {
        backImage.color = Color.white;
        uIEngine.baseObj = null;
        transform.localScale = Vector3.one;
    }


    /// <summary>
    /// 播放声音
    /// </summary>
    private void PlayAudio()
    {
        audioPlayer.clip = audioPress;
        audioPlayer.Play();   // 开始播放
    }

    /// <summary>
    /// 播放点击粒子动画
    /// </summary>
    private void PlayClickParticle()
    {
        // 将鼠标屏幕坐标转换为世界坐标
        Vector3 clickPosition = Camera.main.ScreenToWorldPoint(
            new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10f));
        // 移动粒子系统到点击位置并播放
        clickParticle.transform.position = clickPosition;
        // 直接播放粒子系统
        clickParticle.Play();
    }
}
